<?php
	require_once("obj/user.php");

	$email = "";
	$pwd = "";
	$new = "";
	$new2 = "";
	
	if(isset($_POST["txtEmail"])) {
		$email = $_POST["txtEmail"];
		$pwd = $_POST["txtPassword"];
		$new = $_POST["txtNewPassword"];
		$new2 = $_POST["txtNewPassword2"];
		$user = User::get($email, $pwd);
		if($user != null && $user->UserId != null){
			if(strlen($new) >= 6) {
				$user->changePassword($new);
				echo "<div class='error'>Your password has been changed</div>";
				$email = "";
				$pwd = "";
				$new = "";
				$new2 = "";
			}
			else { 
				echo "<div class='error'>Password must be at least 6 characters</div>";
			}
		}
		else{			
			echo "<div class='error'>Invalid username/password</div>";
		}
	}
?>

<form method="post" action="index.php?page=resetpwd">
	<table border="0" cellpadding="3" cellspacing="0">
		<tr>
			<td>Email:</td>
			<td><input type="input" id="txtEmail" name="txtEmail" value="<?php echo $email;?>" /></td>
		</tr>
		<tr>
			<td>Password:</td>
			<td><input type="password" id="txtPassword" name="txtPassword" value="<?php echo $pwd;?>" /></td>
		</tr>
		<tr>
			<td>New Password:</td>
			<td><input type="password" id="txtNewPassword" name="txtNewPassword" value="<?php echo $new;?>" /></td>
		</tr>
		<tr>
			<td>Confirm Password:</td>
			<td><input type="password" id="txtNewPassword2" name="txtNewPassword2" value="<?php echo $new2;?>" /></td>
		</tr>
		<tr>
			<td>
				<input type="submit" value="Submit" onclick="return validatePasswordReset();" />
				<a href="index.php">Back to login screen</a>
			</td>
		</tr>
	</table>
</form>
<script type="text/javascript">
	function validatePasswordReset() {
		var ok = true;
		var msg = "";
		if(!validateRequired('txtEmail')) {
			msg += "Email is required\n";
			ok = false;
		}
		if(!validateRequired('txtPassword')) {
			msg += "Password is required\n";
			ok = false;
		}
		if(!validateRequired('txtNewPassword')) {
			msg += "New Password is required\n";
			ok = false;
		}
		if(!validateRequired('txtNewPassword2')) {
			msg += "Confirm Password is required\n";
			ok = false;
		}
		
		if(ok && document.getElementById("txtNewPassword").value != document.getElementById("txtNewPassword2").value){
			msg += "New password does not match confirm password";
			ok = false;
		}
		
		if(!ok) alert(msg);
		
		return ok;
	}
</script>